#include <cstdio>
#include <algorithm>
#include <vector>
#include <cstring>
#include <queue>
using namespace std;
const int N=1005;
const int INF=0x3f3f3f3f;
int n;
int m;
int dis[N];
int cnt[N];
bool vis[N];
struct Edge{
    int v;
    int c;
    Edge(int _v,int _c):v(_v),c(_c){}
};
vector<Edge> e[N];
bool spfa(int s){
    memset(vis,false,sizeof(vis));
    memset(cnt,0,sizeof(cnt));
    for(int i=0;i<n+2;i++){
        dis[i]=0;
    }
    //dis[s]=INF;
    vis[s]=true;
    queue<int> q;
    q.push(s);
    cnt[s]=1;
    while(!q.empty()){
        int u=q.front();
        q.pop();
        vis[u]=false;
        for(int i=0;i<e[u].size();i++){
            int v=e[u][i].v;
            int w=e[u][i].c;
            //printf("%d %d %d\n",u,v,w);
            if(dis[v]<dis[u]+w){
                dis[v]=dis[u]+w;
                if(!vis[v]){
                    vis[v]=true;
                    q.push(v);
                    if(++cnt[v]>n){
                        return false;
                    }
                }
            }
        }
    }
    return true;
}
int main(void){
    //freopen("data.txt","r",stdin);
    while(~scanf("%d%d",&n,&m)){
        for(int i=0;i<n+2;i++){
            e[i].clear();
        }
        int u,v,c;
        //增加一个起点和重点
        int s=n;
        int t=n+1;
        while(m--){
            scanf("%d%d%d",&u,&v,&c);
            e[u].push_back(Edge(v,c));
        }
        //边权为1 然后最终结果减掉1
        for(int i=0;i<n;i++){
            e[s].push_back(Edge(i,1));
        }
        for(int i=0;i<n;i++){
            e[i].push_back(Edge(t,1));
        }
        spfa(s);
        printf("%d\n",dis[t]-1);
    }
    return 0;
}